<include file="public@header_vue"/>
<style>
    .el-pagination {
        margin-top: 20px;
    }

    .avatar {
        width: 40px;
        height: auto;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
</style>
</head>
<body>
<div id="app">
    <el-tabs type="border-card">
        <el-tab-pane label="权限管理" v-loading="onDataLoading">
            <el-row>
                <el-col :span="4" style="text-align: left">
                    <el-button type="primary" size="mini" @click="update()">新增</el-button>
                </el-col>
            </el-row>
            <el-table :data="tableData"
                      row-key="id"
                      border
                      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                      style="width: 100%;margin-bottom: 20px;">
                <el-table-column prop="id" label="ID" width="100"></el-table-column>
                <el-table-column prop="name" label="名称" width="150"></el-table-column>
                <el-table-column prop="url" label="前端地址"></el-table-column>
                <el-table-column prop="api_url" label="接口地址"></el-table-column>
                <el-table-column prop="create_time" label="添加时间" width="200">
                    <template slot-scope="scope">
                        {{formatDate(scope.row.create_time)}}
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="180">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="update(scope.row)">编辑</el-button>
                        <el-button size="mini" type="text" @click="delete_source(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
        <el-dialog :title="authForm.id == '' ? '新增菜单' : '修改菜单'" :visible.sync="dialogVisible" width="60%"
                   v-loading.fullscreen="dialogLoading">
            <el-form :model="authForm" class="demo-form-inline" :rules="rules" ref="authForm"
                     label-width="200px">
                <el-form-item label="上级">
                    <el-col :span="18">
                        <el-select v-model="authForm.parent_id" placeholder="请选择上级">
                            <el-option value="0">一级</el-option>
                            <el-option
                                    v-for="item in auth_rule"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-col :span="18">
                        <el-input v-model="authForm.name" placeholder="名称"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="前端地址" prop="url">
                    <el-col :span="18">
                        <el-input v-model="authForm.url" placeholder="前端地址"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="接口地址" prop="api_url">
                    <el-col :span="18">
                        <el-input v-model="authForm.api_url" placeholder="接口地址"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="图标" prop="icon">
                    <el-col :span="18">
                        <el-upload
                                class="avatar-uploader"
                                action="{:url('api/crm/upload')}"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="authForm.icon" :src="authForm.icon" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button v-if="authForm.id === ''" type="primary" @click="submit('authForm')">新增</el-button>
            <el-button v-else type="primary" @click="submit('authForm')">修改</el-button>
        </span>
        </el-dialog>
    </el-tabs>
</div>
</body>
<script>
    let id = 1000;
    var app = new Vue({
        el: '#app',
        data: function () {

            var checkPhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('手机号不能为空'));
                } else {
                    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
                    if (reg.test(value)) {
                        callback();
                    } else {
                        return callback(new Error('请输入正确的手机号'));
                    }
                }
            };
            let self = this;
            return {
                tableData: [],
                form: {
                    keyword: '',
                },
                authForm: {
                    id: '',
                    name: '',
                    url: '',
                    api_url: '',
                    icon: '',
                    parent_id: 0,
                },
                dialogVisible: false,
                dialogLoading: true,
                roleData: [],
                totalNum: 0,
                currentPage: 1,
                parent_info: [],
                show_name: {
                    label: 'name'
                },
                onDataLoading: false,
                headers: {'X-Requested-With': 'XMLHttpRequest'},
                rules: {
                    name: [{required: true, message: '请输入菜单名称', trigger: 'blur'}],
                    api_url: [{required: true, message: '请输入接口地址', trigger: 'blur'}],
                },
                auth_rule: [],
            };
        },
        created() {
            this.getData()
            this.get_role()
        },
        methods: {
            clearForm() {
                this.form = {
                    name: '',
                }
            },
            handleAvatarSuccess(res, file) {
                console.log(res.url)
                this.imageUrl = URL.createObjectURL(file.raw);
                this.authForm.icon = res.url;
            },
            beforeAvatarUpload(file) {
                console.log(file)
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG/png 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            get_role() {
                let _this = this;
                this.onDataLoading = true;
                axios.get("{:url('admin/role/get_all_oauth')}", {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'

                    }
                }).then(function (response) {
                    console.log(response);
                    _this.onDataLoading = false;
                    if (response.data.code === 1) {
                        _this.auth_rule = response.data.data;
                    } else {
                        _this.$message({
                            message: response.data.msg,
                            type: 'warning'
                        });
                    }
                }).catch(function (error) {
                    _this.onDataLoading = false;
                    _this.$message.error(error.toString())
                })
            },
            assign_permissions(node, data) {
                console.log(data)
            },
            update(data) {
                let _this = this;
                if (data) {
                    _this.authForm = data
                } else {
                    _this.authForm = {
                        id: '',
                        name: '',
                        url: '',
                        api_url: '',
                        icon: '',
                        parent_id: '',
                    }
                }
                _this.dialogVisible = true;
                _this.dialogLoading = false;
            },
            append(data) {
                let _this = this;
                console.log(data)
                _this.dialogVisible = true;
                _this.roleFrom.parent_id = data.parent_id;
                _this.dialogLoading = false;
            },
            submit(form) {
                let _this = this;
                _this.$refs[form].validate((valid) => {
                    if (valid) {
                        axios.post("{:url('admin/role/update_auth')}", this.authForm, {
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                            }
                        }).then(function (response) {
                            _this.dialogLoading = false;
                            if (response.data.code === 1) {
                                if (_this.authForm.id === '') {
                                    _this.$message.success('新增完成');
                                } else {
                                    _this.$message.success('修改成功');
                                }
                                _this.getData();
                                _this.dialogVisible = false;
                            } else {
                                _this.$message.warning(response.data.msg);
                            }
                        }).catch(function (error) {
                            _this.dialogLoading = false;
                            _this.$message.error(error.toString())
                        })
                    } else {
                        _this.dialogLoading = false;
                        return false;
                    }
                });
            },
            remove(node, data) {
                let _this = this;
                const parent = node.parent;
                const children = parent.data.children || parent.data;
                const index = children.findIndex(d => d.id === data.id);
                console.log(children[index].children)
                if (children[index].children == undefined || children[index].children.length == 0) {
                    children.splice(index, 1);
                } else {
                    _this.$message.error('该角色下还有未删除的角色');
                }
            },
            delete_source(id) {
                let _this = this;
                let params = {id: id};
                axios.get("{:url('admin/role/delete_oauth')}", {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                    params: params
                }).then(function (response) {
                    console.log(response);
                    _this.onDataLoading = false;
                    if (response.data.code === 1) {
                        _this.$message.success('删除成功');
                        _this.getData();
                    } else {
                        _this.$message({
                            message: response.data.msg,
                            type: 'warning'
                        });
                    }
                }).catch(function (error) {
                    _this.onDataLoading = false;
                    _this.$message.error(error.toString())
                })
            },
            //首页获取列表数据
            getData() {
                let _this = this;
                this.onDataLoading = true;
                if (this.form.keyword !== '') {
                    params.keyword = this.form.keyword;
                }
                axios.get("{:url('admin/role/oauth')}", {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                }).then(function (response) {
                    console.log(response);
                    _this.onDataLoading = false;
                    if (response.data.code === 1) {
                        _this.tableData = response.data.data;
                    } else {
                        _this.$message({
                            message: response.data.msg,
                            type: 'warning'
                        });
                    }
                }).catch(function (error) {
                    _this.onDataLoading = false;
                    _this.$message.error(error.toString())
                })
            },

            formatDate(timestamp) {
                let date = new Date(timestamp * 1000);
                return date.getFullYear() + '-' + this.prefix(date.getMonth() + 1) + '-' + this.prefix(date.getDate()) + ' ' + this.prefix(date.getHours()) + ':' + this.prefix(date.getMinutes()) + ':' + this.prefix(date.getSeconds());
            },
            prefix(num) {
                if (num < 10) {
                    return '0' + num;
                }
                return num;
            }
        }
    });
</script>
